package com.wswy.wzcx.widget.home

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Typeface
import android.graphics.drawable.ColorDrawable
import android.support.v4.content.ContextCompat
import android.text.SpannableString
import android.text.SpannableStringBuilder
import android.text.TextPaint
import android.text.TextUtils
import android.text.style.*
import android.util.AttributeSet
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.widget.FrameLayout
import com.blankj.utilcode.util.SizeUtils
import com.blankj.utilcode.util.TimeUtils
import com.facebook.drawee.drawable.ScalingUtils
import com.facebook.drawee.generic.RoundingParams
import com.wswy.wzcx.R
import com.wswy.wzcx.model.CarTypes
import com.wswy.wzcx.model.car.CarStatus
import com.wswy.wzcx.model.license.UserCarInfo
import com.wswy.wzcx.module.base.onClick
import com.wswy.wzcx.ui.car.remind.RemindActivity
import com.wswy.wzcx.ui.car.result.QueryResultActivity
import com.wswy.wzcx.utils.StringUtils
import com.wswy.wzcx.utils.UiUtils
import com.wswy.wzcx.widget.home.IHomeCarLayout.Companion.SIZE
import com.wswy.wzcx.widget.utils.VerticalCenterSpan
import kotlinx.android.synthetic.main.item_layout_home_car_info2.view.*
import timber.log.Timber
import kotlin.math.abs
import kotlin.math.max

class CarInfoLayout : FrameLayout,IHomeCarLayout {

    constructor(context: Context) : this(context, null)

    constructor(context: Context, attribute: AttributeSet?) : this(context, attribute, 0)

    constructor(context: Context, attribute: AttributeSet?, defStyle: Int) : super(context, attribute, defStyle) {

    }

    init {
        LayoutInflater.from(context).inflate(R.layout.item_layout_home_car_info2, this)

    }

    override fun alpha(alpha: Float) {

        this.alpha = alpha
    }

    private var hasCarLogo = false

    override fun setData(userCarInfo: UserCarInfo?) {

        userCarInfo?.run {



            tv_car_no.text  = SpannableStringBuilder().apply {
                if (TextUtils.isEmpty(carNo)){
                    append("未知车牌")
                }else{
                    append(carNo)
                }


                //新能源车
                if (CarTypes.isNECar(carType)){
                    append(SpannableString("#").apply {
                        setSpan(ImageSpan(context,R.drawable.car_nengyuan, DynamicDrawableSpan.ALIGN_BASELINE),0,1,SpannableString.SPAN_INCLUSIVE_EXCLUSIVE)
                    })
                }

            }

            val logo = carExtendInfo?.carTypeData?.series?.logo

            if (!TextUtils.isEmpty(logo?.trim())){


                (img_car_icon.layoutParams as? MarginLayoutParams)?.run {


                    width = SizeUtils.dp2px(72f)
                    height = width
                    topMargin = SizeUtils.dp2px(24f)
                    rightMargin = SizeUtils.dp2px(40f)
                    img_car_icon.layoutParams = this
                }

                img_car_icon.hierarchy?.run {
                    setBackgroundImage(ColorDrawable(Color.WHITE))
                    roundingParams = RoundingParams.asCircle()

                    actualImageScaleType = ScalingUtils.ScaleType.FIT_CENTER
                    img_car_icon.hierarchy = this
                }
                img_car_icon.setImageURI(logo)

                //防止刷新位置不对
                UiUtils.addOnGlobalLayoutListener(img_car_icon){

                    animOffset(0f)
                }

                hasCarLogo = true
            }else{

                img_car_icon.setImageURI(logo)
            }


            tv_car_fine_info.text = resources.getString(R.string.last_query, StringUtils.formatTime(getLastDate().time))

            carExtendInfo?.run {

                inspection?.run {

                    tv_njtx_hint.text =when(status){
                        CarStatus.NORMAL -> {
                            //安全
                            "年检办理(天)"
                        }
                        CarStatus.PROMPT -> {
                            //可办
                            "年检到期(天)"
                        }
                        CarStatus.OVERDUE -> {
                            //逾期
                            "已逾期(天)"
                        }
                        else -> ""
                    }

                    tv_njtx.text = "$remainDay"
                    tv_njtx.setCompoundDrawables(null,null,null,null)
                } ?: kotlin.run {
                    tv_njtx_hint.text = "年检提醒"
                    tv_njtx.text = null
                    ContextCompat.getDrawable(context,R.drawable.card_addnew)?.let {
                        it.setBounds(0,0,SizeUtils.dp2px(16f),SizeUtils.dp2px(16f))
                        tv_njtx.setCompoundDrawables(it,null,null,null)
                    }
                }


                valuation?.run {
                    tv_acgz_hint.text = "估值(万元)"
                    tv_acgz.text = "${value}"
                    tv_acgz.setCompoundDrawables(null,null,null,null)
                }?:kotlin.run {
                    tv_acgz_hint.text = "爱车估值"
                    tv_acgz.text = null
                    ContextCompat.getDrawable(context,R.drawable.card_addnew)?.let {
                        it.setBounds(0,0,SizeUtils.dp2px(16f),SizeUtils.dp2px(16f))
                        tv_acgz.setCompoundDrawables(it,null,null,null)
                    }
                }



            }?:kotlin.run {
                tv_njtx_hint.text = "年检提醒"
                tv_njtx.text = null
                ContextCompat.getDrawable(context,R.drawable.card_addnew)?.let {
                    it.setBounds(0,0,SizeUtils.dp2px(16f),SizeUtils.dp2px(16f))
                    tv_njtx.setCompoundDrawables(it,null,null,null)
                }

                tv_acgz_hint.text = "爱车估值"
                tv_acgz.text = null
                ContextCompat.getDrawable(context,R.drawable.card_addnew)?.let {
                    it.setBounds(0,0,SizeUtils.dp2px(16f),SizeUtils.dp2px(16f))
                    tv_acgz.setCompoundDrawables(it,null,null,null)
                }
            }


            tv_fine_count.text = trafficCount.toString()
//            tv_fine_point.text = totalScore.toString()
//            tv_fine_fee.text = totalFee.toString()
        }

    }

    private val dp40 by lazy {
        SizeUtils.dp2px(40f).toFloat()
    }


    private val dp30 by lazy {
        SizeUtils.dp2px(30f).toFloat()
    }

    override fun hideLeft() {


        ll_car_info.y = 300f
        img_car_icon.x = SIZE.screenWidget/2

        ll_car_info.alpha = 0f
        img_car_icon.alpha = 0f


        x = -SIZE.screenWidget //重要，避免view重叠影响点击事件
    }

    override fun hideRight() {
        ll_car_info.y = -300f
        img_car_icon.x = - SIZE.screenWidget
        ll_car_info.alpha = 0f
        img_car_icon.alpha = 0f

        x = SIZE.screenWidget
    }

    private var maxS = 0

    override fun animOffset(offset: Float) {
        x = 0f //开始做动画时恢复到初始位置

        if (img_car_icon.width == 0){

            postOnAnimation {
                requestLayout()
                maxS ++
                if (maxS < 30){
                    animOffset(offset)
                }
            }

            return
        }else{
            maxS = 0
        }

        ll_car_info.y = SizeUtils.dp2px(18f) + dp30 * (offset*-1)
        ll_car_info.alpha = 1 - abs(offset)

        //0.768

        val sw = SIZE.screenWidget - SizeUtils.dp2px(9f) //减去间距
        val wf = sw - SIZE.screenWidget * (1 - 0.79f) - img_car_icon.width / 2
        img_car_icon.x = wf + (sw - wf) * offset

        //加速显示/隐藏
        img_car_icon.alpha = max(1 - abs(offset)*1.1f,0f)


        layout_bottom_car_info.alpha = 1- abs(offset)

        if (offset > 0){
            layout_bottom_car_info.y = SizeUtils.dp2px(126f) - dp40 * (1-offset)
        }else if (offset <= 0){
            layout_bottom_car_info.y = SizeUtils.dp2px(86f) + dp40 * abs(offset)
        }

        layout_bottom_car_info.layoutParams.run {

            height = (dp40 -  ((20f) - 20f  *(1- abs(offset)) )).toInt()

            layout_bottom_car_info.layoutParams = this
        }


        img_refresh.rotation = (1- offset)*360f

    }

    override fun getView(): View = this



    class MyRelativeSizeSpan(private val color:Int,private val fontSizeSp:Float):ReplacementSpan(){
        override fun getSize(paint: Paint, text: CharSequence?, start: Int, end: Int, fm: Paint.FontMetricsInt?): Int {
            val p = makeTextSpan(paint)
            return p.measureText(text?.subSequence(start, end)?.toString()).toInt()
        }

        override fun draw(canvas: Canvas, text: CharSequence?, start: Int, end: Int, x: Float, top: Int, y: Int, bottom: Int, paint: Paint) {
            text?.subSequence(start, end)?.toString()?.let {
                val p = makeTextSpan(paint)
                val fm = p.fontMetricsInt
                canvas.drawText(it, x+8, (y - ((y + fm.descent + y + fm.ascent) / 2 - (bottom + top) / 2)).toFloat(), p)    //使字体居中


                Timber.e("------$it")
            }
        }


        private fun makeTextSpan(srcPaint: Paint): TextPaint {
            val paint = TextPaint(srcPaint)
            paint.color = color
            paint.textSize = SizeUtils.sp2px(fontSizeSp).toFloat()
            return paint
        }
    }


    private class MyColorSpan(private val color:Int) :ReplacementSpan() {
        override fun getSize(paint: Paint, text: CharSequence?, start: Int, end: Int, fm: Paint.FontMetricsInt?): Int {
            return paint.measureText(text.toString()).toInt()+8
        }

        override fun draw(canvas: Canvas, text: CharSequence?, start: Int, end: Int, x: Float, top: Int, y: Int, bottom: Int, paint: Paint) {
            canvas.drawText(text.toString(),start,end,x+8,y.toFloat(),paint)

        }

    }

}